package com.yang.common.advice;

import com.yang.common.annotation.RedisLimitAnnotation;
import com.yang.common.exception.BusinessException;
import com.yang.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Billyang
 * @date: 2024/9/28 22:04
 */
@Component
@Aspect
@Slf4j
public class RedisLimitAdvice {

    private Object result = null;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> redisLuaScript;

    @PostConstruct
    public void init() {
        redisLuaScript = new DefaultRedisScript<>();
        redisLuaScript.setResultType(Long.class);
        redisLuaScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    @Around("@annotation(com.yang.common.annotation.RedisLimitAnnotation)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        log.info("RedisLimitAdvice start.....");
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        RedisLimitAnnotation redisLimitAnnotation = method.getAnnotation(RedisLimitAnnotation.class);
        if (redisLimitAnnotation != null) {
            //获取redis的key
            String key = redisLimitAnnotation.key();
            String className = method.getDeclaringClass().getName();
            String methodName = method.getName();

            String limitKey = key + ":" + className + ":" + methodName;
            log.info("RedisLimitAdvice limitKey:{}", limitKey);

            if (null == key) {
                throw new BusinessException("it's danger,limitKey cannot be null");
            }

            long limit = redisLimitAnnotation.permitsPerSecond();
            long expire = redisLimitAnnotation.expire();
            List<String> keys = new ArrayList<>();
            keys.add(key);
            Long count = stringRedisTemplate.execute(redisLuaScript, keys, String.valueOf(limit), String.valueOf(expire));
            System.out.println("Access try count is " + count + " \t key= " + key);
            if (count != null && count == 0) {
                log.info("启动限流功能key: {}", key);
                return ResponseResult.errorResult(1000, redisLimitAnnotation.msg());
            }
        }
        try {
            result = pjp.proceed();//放行
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        log.info("RedisLimitAdvice end.....");
        return result;
    }

    /**
     * 构建redis lua脚本,防御性编程，程序员自我保护，闲聊
     * 能用LuaScript，就不要用java拼装
     * @return
     */
    /*private String buildLuaScript() {
        StringBuilder luaString = new StringBuilder();
        luaString.append("local key = KEYS[1]");
        //获取ARGV内参数Limit
        luaString.append("\nlocal limit = tonumber(ARGV[1])");
        //获取key的次数
        luaString.append("\nlocal curentLimit = tonumber(redis.call('get', key) or '0')");
        luaString.append("\nif curentLimit + 1 > limit then");
        luaString.append("\nreturn 0");
        luaString.append("\nelse");
        //自增长 1
        luaString.append("\n redis.call('INCRBY', key, 1)");
        //设置过期时间
        luaString.append("\nredis.call('EXPIRE', key, ARGV[2])");
        luaString.append("\nend");
        return luaString.toString();
    }*/

}
